"""Prometheus metrics configuration."""
from prometheus_flask_exporter import PrometheusMetrics
from prometheus_client import Counter, Histogram, Gauge, Info
from flask import Flask
import time


# Custom metrics
api_requests_total = Counter(
    'buyu_api_requests_total',
    'Total API requests',
    ['method', 'endpoint', 'status']
)

api_request_duration = Histogram(
    'buyu_api_request_duration_seconds',
    'API request duration in seconds',
    ['method', 'endpoint']
)

active_sessions = Gauge(
    'buyu_active_sessions',
    'Number of active walking sessions'
)

music_generation_total = Counter(
    'buyu_music_generation_total',
    'Total music generation requests',
    ['status']
)

music_generation_duration = Histogram(
    'buyu_music_generation_duration_seconds',
    'Music generation duration in seconds'
)

poi_detections_total = Counter(
    'buyu_poi_detections_total',
    'Total POI detections'
)

weather_api_calls = Counter(
    'buyu_weather_api_calls_total',
    'Total weather API calls',
    ['status']
)

cache_hits = Counter(
    'buyu_cache_hits_total',
    'Total cache hits',
    ['cache_type']
)

cache_misses = Counter(
    'buyu_cache_misses_total',
    'Total cache misses',
    ['cache_type']
)

celery_task_duration = Histogram(
    'buyu_celery_task_duration_seconds',
    'Celery task duration in seconds',
    ['task_name']
)

celery_task_status = Counter(
    'buyu_celery_task_status_total',
    'Celery task status',
    ['task_name', 'status']
)

app_info = Info(
    'buyu_app',
    'Application information'
)


def setup_metrics(app: Flask):
    """Configure Prometheus metrics.
    
    Args:
        app: Flask application instance
    """
    try:
        # Initialize Prometheus metrics
        metrics = PrometheusMetrics(app)
        
        # Set application info
        app_info.info({
            'version': '1.0.0',
            'environment': app.config.get('ENV', 'unknown')
        })
        
        # Exclude health check endpoint from metrics if metrics object exists
        if metrics and hasattr(metrics, 'excluded_paths'):
            metrics.excluded_paths.append('/health')
        
        # Custom request counter
        @app.before_request
        def before_request_metrics():
            """Record request start time."""
            from flask import g, request
            g.start_time = time.time()
        
        @app.after_request
        def after_request_metrics(response):
            """Record request metrics."""
            from flask import g, request
            
            if hasattr(g, 'start_time'):
                duration = time.time() - g.start_time
                
                # Record metrics
                api_requests_total.labels(
                    method=request.method,
                    endpoint=request.endpoint or 'unknown',
                    status=response.status_code
                ).inc()
                
                api_request_duration.labels(
                    method=request.method,
                    endpoint=request.endpoint or 'unknown'
                ).observe(duration)
            
            return response
        
        app.logger.info("Prometheus metrics initialized at /metrics")
        
        return metrics
    except Exception as e:
        app.logger.warning(f"Failed to initialize Prometheus metrics: {e}")
        return None


def record_music_generation(duration: float, success: bool):
    """Record music generation metrics.
    
    Args:
        duration: Generation duration in seconds
        success: Whether generation was successful
    """
    status = 'success' if success else 'failure'
    music_generation_total.labels(status=status).inc()
    music_generation_duration.observe(duration)


def record_poi_detection():
    """Record POI detection event."""
    poi_detections_total.inc()


def record_weather_api_call(success: bool):
    """Record weather API call.
    
    Args:
        success: Whether the call was successful
    """
    status = 'success' if success else 'failure'
    weather_api_calls.labels(status=status).inc()


def record_cache_access(cache_type: str, hit: bool):
    """Record cache access.
    
    Args:
        cache_type: Type of cache (e.g., 'weather', 'poi')
        hit: Whether it was a cache hit
    """
    if hit:
        cache_hits.labels(cache_type=cache_type).inc()
    else:
        cache_misses.labels(cache_type=cache_type).inc()


def update_active_sessions(count: int):
    """Update active sessions gauge.
    
    Args:
        count: Current number of active sessions
    """
    active_sessions.set(count)


def record_celery_task(task_name: str, duration: float, status: str):
    """Record Celery task metrics.
    
    Args:
        task_name: Name of the task
        duration: Task duration in seconds
        status: Task status (success, failure, retry)
    """
    celery_task_duration.labels(task_name=task_name).observe(duration)
    celery_task_status.labels(task_name=task_name, status=status).inc()
